// pages/player/player.js
import api from '../../utils/api';
import { myRequest } from '../../utils/request';
import Cache from '../../utils/cache';
import Tool from '../../utils/tool';
const app = getApp();

// 获取全局唯一的背景音频管理器
const backgroundAudioManager = wx.getBackgroundAudioManager()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 当前机型的状态栏高度
        barHeight: 0,
        music: {}, // 当前音乐信息
        isCollect: false, // 是否收藏音乐
        isShowPlayList: false,  // 是否展示播放列表
        isPlaying: false, // 是否正在播放
        isLyricsShow: false, // 是否展示歌词
        lyricsIndex: 0, // 歌词索引
        lyricsList: [], // 歌词列表
        playerList: [], // 播放列表
        duration: 0, // 歌曲时长
        sliderValue: 0, // 进度条滑动值
        playType: 1,  // 播放类型  1：列表循环  2：单曲循环  3：随机播放
        isShowAddMusicMenu: false, // 是否展示添加歌单页面
        musicMenuName: '', // 歌单名称
        musicMenuList: [], // 个人歌单列表
        showTime: {
          currentTime: '00:00',
          totalTime: '00:00'
        }
    },

    /**
    * 验证用户是否登录
    */
    authUser() {
      const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
      if(Tool.isEmpty(loginUser)) {
          wx.reLaunch({
              url: '/pages/login/login'
          })
      }
  },

  onShareAppMessage: function (res) {
    //console.log('onShareAppMessage',res);
    return {
      title: "歌曲分享",
      path: "/pages/player/player?music=" + JSON.stringify(this.data.music),
    }
  },



   /**
   * 生命周期函数--监听页面加载
   */
   onLoad: async function (options) {
    // 获取当前机型的状态栏高度
    wx.getSystemInfo({
      success: e => {
        // e.statusBarHeight; //状态栏高
        // console.log(e.statusBarHeight);
        this.setData({
          barHeight: e.statusBarHeight
        })
      }
    });

    // 监听isPlaying变化
    app.watch(this, {
      isPlaying: function (newVal) {
        app.setIsPlaying(newVal);
      },
      playType: function (newVal) {
        app.setPlayType(newVal);
      }
    })
   
    let music = JSON.parse(options.music);

    // 获取歌词数据
    await this.getMusicLyricsList(music.id);

    // 如果当前歌曲没有在播放  或者  当前播放的歌曲和现在进入的歌曲不一致
    if(!app.getIsPlaying() || music.id !== app.getPlayMusicId()) {
      wx.showLoading({
        title: '歌曲加载中...',
        mask: true
      })
      backgroundAudioManager.pause();
      this.setData({isPlaying: false});
      this.addMusicListenNum(music.id);
    }

    // 如果当前歌曲正在播放，而且再次进入的是当前正在播放的歌曲
    if(app.getIsPlaying() && music.id === app.getPlayMusicId()) {
      backgroundAudioManager.play();
      this.setTime();
      this.setData({isPlaying: true});
      // 歌词校准
      if(!isNaN(Math.floor(backgroundAudioManager.currentTime))) {
        this.getCurrentLyricsIndex(Math.floor(backgroundAudioManager.currentTime)); 
      }
    }

    if(app.getPlayType()) {
      this.setData({playType: app.getPlayType()});
    }

    // 判断是否收藏了这首歌
    await this.selectIsCollect(music.id);
    // 添加最新播放音乐数据
    await this.addRecentListenMusic(music.id);

    music.coverPhoto = api.BASE_URL + '/photo/view?filename=' + music.coverPhoto;
    app.setPlayMusicId(music.id);
    // 获取播放列表数据
    if(typeof options.albumId != 'undefined') {
      wx.removeStorageSync('playerList');
      await this.getMusicListByAlbumId(options.albumId);
    } else if (typeof options.musicMenuId != 'undefined') {
      wx.removeStorageSync('playerList');
      await this.getMusicListByMusicMenuId(options.musicMenuId);
    } else if (typeof options.singerId != 'undefined') {
      wx.removeStorageSync('playerList');
      await this.getMusicListBySingerId(options.singerId);
    } else {
      // 从缓存中获取播放列表
      let playerListString = wx.getStorageSync('playerList');
      if(!playerListString) {
        playerListString = "[]";
      }
      let playerList = JSON.parse(playerListString);
      let flag = false; // 是否存在
      playerList.forEach(item => {
        if(item.id === music.id) {
          flag = true;
        }
      })
      if(!flag) {
        playerList.push(music);
        wx.setStorageSync('playerList', JSON.stringify(playerList));
      }
      this.setData({playerList: playerList});
    }
   
  
    // 绑定backgroundAudioManager的事件
    this.bindBGMEvent();
    this.setData({music: music});
   
    backgroundAudioManager.src = api.BASE_URL + "/music/view?filename=" + music.file;
    backgroundAudioManager.title = music.name;
    
  },

  // 增加播放数
  async addMusicListenNum(musicId) {
    const res = await myRequest({
      url: '/app/music/addListen',
      method: 'POST',
      data: {id: musicId}
    });
  },

  // 判断当前用户是否收藏音乐
  async selectIsCollect(musicId) {
    const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
    const res = await myRequest({
      url: '/app/collect/isCollect',
      method: 'POST',
      data: {musicId: musicId, token: loginUser}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        this.setData({isCollect: result});
    }
  },

  // 添加最新播放数据
  async addRecentListenMusic(musicId) {
    const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
    const res = await myRequest({
      url: '/app/recent/listen/add',
      method: 'POST',
      data: {musicId: musicId, token: loginUser}
    });
  },

  // 收藏音乐或取消收藏
  async collectOrCancel() {
    const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
    if(Tool.isEmpty(loginUser)) {
        wx.reLaunch({
            url: '/pages/login/login'
        })
    }
    const { isCollect, music } = this.data;
    if(isCollect === false) {
      // 收藏操作
      const res = await myRequest({
        url: '/app/collect/add',
        method: 'POST',
        data: {musicId: music.id, token: loginUser}
      });
      if(res.data.code === 0) {
          wx.showToast({
            title: '收藏成功！',
            icon: 'success'
          })
          this.setData({isCollect: true});
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    } else {
      // 取消收藏操作
      const res = await myRequest({
        url: '/app/collect/remove',
        method: 'POST',
        data: {musicId: music.id, token: loginUser}
      });
      if(res.data.code === 0) {
          wx.showToast({
            title: '取消收藏成功！',
            icon: 'success'
          })
          this.setData({isCollect: false});
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    }
  },

  changePlayType() {
    const { playType } = this.data;
    if(playType === 1) {
      this.setData({playType: 2});
      wx.showToast({
        title: '切换到单曲循环',
        icon: 'none'
      })
    } else if (playType === 2) {
      this.setData({playType: 3});
      wx.showToast({
        title: '切换到随机播放',
        icon: 'none'
      })
    } else if(playType === 3) {
      this.setData({playType: 1});
      wx.showToast({
        title: '切换到列表循环',
        icon: 'none'
      })
    }
  },

  // 根据专辑id获取音乐数据
  async getMusicListByAlbumId(albumId) {
    const res = await myRequest({
      url: '/app/music/getByAlbumId',
      method: 'POST',
      data: {albumId: albumId}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        result.forEach(item => {
          item.coverPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
        })
        this.setData({playerList: result});
    }
  },

  // 根据歌单id获取音乐数据
  async getMusicListByMusicMenuId(musicMenuId) {
    const res = await myRequest({
      url: '/app/music/getByMusicMenuId',
      method: 'POST',
      data: {id: musicMenuId}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        result.forEach(item => {
          item.coverPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
        })
        this.setData({playerList: result});
    }
  },

  // 根据歌手id获取音乐数据
  async getMusicListBySingerId(singerId) {
    const res = await myRequest({
      url: '/app/music/getBySingerId',
      method: 'POST',
      data: {singerId: singerId}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        result.forEach(item => {
          item.coverPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
        })
        this.setData({playerList: result});
    }
  },

  // 添加音乐到歌单中
  async addMusicMenu(event) {
    const data = event.currentTarget.dataset;
    const res = await myRequest({
      url: '/app/music/menu/add',
      method: 'POST',
      data: {musicId: this.data.music.id, musicMenuId: data.id}
    });
    if(res.data.code === 0) {
      wx.showToast({
        title: res.data.msg,
        icon: 'success'
      })
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
    }
  },

  // 展示添加歌单页面
  showAddMusicMenu() {
    this.authUser();
    this.getSelfMusicMenu();
    this.setData({isShowAddMusicMenu: true});
  },

  // 隐藏添加歌单页面
  hideList() {
    this.setData({isShowAddMusicMenu: false});
  },


  async getMusicLyricsList(id) {
    const res = await myRequest({
      url: '/app/lyrics/getByMusicId',
      method: 'POST',
      data: {musicId: id}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        this.setData({lyricsList: result});
    }
  },

  // 拖动进度条动作结束后的回调
  handleSliderChange(e) {
    const { duration } = this.data;
    
    const progress = e.detail.value / 100;
    // 当前拖动到的时间  单位s
    const currentTime = Math.floor(progress * duration);
    backgroundAudioManager.seek(currentTime);
    // 歌词校准
    this.getCurrentLyricsIndex(currentTime);
    const durationFmt = this.dateFormat(currentTime);
    this.setData({
      ['showTime.currentTime']: `${durationFmt.min}:${durationFmt.sec}`,
       sliderValue: e.detail.value
    });
    
  },

  // 切换歌词是否显示
  switchShow() {
    this.setData({isLyricsShow: !this.data.isLyricsShow, });
    if(this.data.isLyricsShow) {
      this.setData({
        lyricsIndex: this.data.lyricsIndex
      });
    }
  },

   // 输入框内容发生改变的回调
   handleInput(event) {
    let type = event.currentTarget.dataset.type;  // data-key=value 传值   用data-key形式可以传多个数据 而id是唯一的
    this.setData({
        // type是变量，对象里面操作属性用中括号
        [type]: event.detail.value
    })
},

  // 创建歌单
  async createMusicMenu() {
    const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
    const res = await myRequest({
      url: '/app/music/menu/save',
      method: 'POST',
      data: {name: this.data.musicMenuName, token: loginUser}
    });
    if(res.data.code === 0) {
        wx.showToast({
          title: '创建成功！',
          icon: 'success'
        })
        this.getSelfMusicMenu();
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
    }
  },

  // 处理滑动时间后的歌词校准
  getCurrentLyricsIndex(time) {
    let lyricsList = this.data.lyricsList;
    if(lyricsList.length === 0) {
      return;
    }
    if (time > (lyricsList[lyricsList.length - 1].minuteTime * 60 + lyricsList[lyricsList.length - 1].secondTime)) {
      this.setData({
        lyricsIndex: lyricsList.length
      })
      return;
    }
    let lyricsIndex = lyricsList.findIndex(item => {
      return time <= (item.minuteTime * 60 + item.secondTime)
    })
    this.setData({
      lyricsIndex: lyricsIndex
    })
  },

  // 绑定背景音乐事件
  bindBGMEvent() {
    backgroundAudioManager.onCanplay(() => {
      console.log('onCanplay')
      this.setData({isPlaying: true});
      backgroundAudioManager.play();
      wx.hideLoading();
      if (typeof backgroundAudioManager.duration != 'undefined') {
        this.setTime()
      } else {
        setTimeout(() => {
          this.setTime()
        }, 1000)
      }
    });

    // 记录上一次的时间  每秒更新一次  节流
    let lastTime = 0;
    backgroundAudioManager.onTimeUpdate(() => {
      const { duration } = this.data;
      let currentTime = Math.floor(backgroundAudioManager.currentTime);
      let progress = Math.floor(currentTime / duration * 100);
      if(lastTime !== currentTime) {
        const durationFmt = this.dateFormat(currentTime);
        if (this.data.lyricsIndex < this.data.lyricsList.length) {
          let lyrics = this.data.lyricsList[this.data.lyricsIndex];
          if (currentTime >= (lyrics.minuteTime * 60 + lyrics.secondTime)) {
            let lyricsIndex = this.data.lyricsIndex + 1
            this.setData({
              lyricsIndex: lyricsIndex
            })
          }
        };
        this.setData({
          ['showTime.currentTime']: `${durationFmt.min}:${durationFmt.sec}`,
          sliderValue: progress
        })
        lastTime = currentTime;
      }
     
    });
    backgroundAudioManager.onPause(() => {
      console.log("pause");
      this.setData({isPlaying: false});
    });
    backgroundAudioManager.onPlay(() => {
      console.log("play");
      wx.hideLoading();
      this.setData({isPlaying: true});
    });
    backgroundAudioManager.onWaiting(() => {
      console.log("waiting...");
      backgroundAudioManager.pause();
      this.setData({isPlaying: false});
      wx.showLoading({
        title: '歌曲加载中...',
        mask: true
      })
    });
    backgroundAudioManager.onEnded(async () => {
      console.log("end");
      backgroundAudioManager.stop();
      this.setData({isPlaying: false});

      const { playType, playerList, music } = this.data;
      let musicIndex = 0;
      let newPlayList = [];
      playerList.forEach((item, index) => {
        if(item.id === music.id) {
          musicIndex = index;
        } else {
          newPlayList.push(item);
        }
      });
      let newMusic = {}; // 即将播放的音乐
      if(playType === 1) {
        // 列表循环
        if(musicIndex === playerList.length - 1) {
          newMusic = playerList[0]
        } else {
          newMusic = playerList[musicIndex + 1]
        }
      } else if (playType === 2) {
        // 单曲循环
        newMusic = music;
      } else if (playType === 3) {
        // 随机播放
        newMusic = newPlayList[Math.floor((Math.random()*newPlayList.length))];
      }
      app.setPlayMusicId(newMusic.id);
      // 添加最近播放歌曲数据
      await this.addRecentListenMusic(newMusic.id);
      // 获取歌词数据
      await this.getMusicLyricsList(newMusic.id);
      // 判断是否收藏
      await this.selectIsCollect(newMusic.id);
      // 歌词校准
      this.getCurrentLyricsIndex(0);
      // 开始播放
      this.setData({isPlaying: true, music: newMusic});
      backgroundAudioManager.src = api.BASE_URL + "/music/view?filename=" + newMusic.file;
      backgroundAudioManager.title = newMusic.name;
      wx.showLoading({
       title: '歌曲加载中...',
       mask: true
      })
    });
   
  },

  // 切换上一首或下一首音乐
  async changeLastOrNextMusic(event) {
    const { playerList, music } = this.data;
    const data = event.currentTarget.dataset
    let type = data.type;
    if(playerList.length <= 1) {
      wx.showToast({
        title: type === 'next' ? '没有下一首歌曲了哦~' : '没有上一首歌曲了哦~',
        icon: 'none'
      })
      return false;
    }
    backgroundAudioManager.stop();
    this.setData({isPlaying: false});
    let musicIndex = 0;
    let newPlayList = [];
    playerList.forEach((item, index) => {
      if(item.id === music.id) {
        musicIndex = index;
      } else {
        newPlayList.push(item);
      }
    });
    let newMusic = {}; // 即将播放的音乐
    if(type === 'next') {
      // 切换下一首歌曲
      if(musicIndex === playerList.length - 1) {
        newMusic = playerList[0]
      } else {
        newMusic = playerList[musicIndex + 1]
      }
    } else {
      // 切换上一首歌曲
      if(musicIndex === 0) {
        newMusic = playerList[playerList.length - 1]
      } else {
        newMusic = playerList[musicIndex - 1]
      }
    }
    
    app.setPlayMusicId(newMusic.id);
   
    // 获取歌词数据
    await this.getMusicLyricsList(newMusic.id);
    // 歌词校准
    this.getCurrentLyricsIndex(0);
    // 判断是否收藏
    await this.selectIsCollect(newMusic.id);
    // 添加最近播放歌曲数据
    await this.addRecentListenMusic(newMusic.id);
    // 开始播放
    this.setData({isPlaying: true, music: newMusic});
    backgroundAudioManager.src = api.BASE_URL + "/music/view?filename=" + newMusic.file;
    backgroundAudioManager.title = newMusic.name;
    wx.showLoading({
     title: '歌曲加载中...',
     mask: true
    })
  },

  setTime() {
    const duration = backgroundAudioManager.duration
    const durationFmt = this.dateFormat(duration)
    this.setData({
      ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`,
      duration: duration
    })
  },

  // 格式化时间
  dateFormat(sec) {
    // 分钟
    const min = Math.floor(sec / 60)
    sec = Math.floor(sec % 60)
    return {
      'min': this.parse0(min),
      'sec': this.parse0(sec),
    }
  },
  // 补零
  parse0(sec) {
    return sec < 10 ? '0' + sec : sec
  },

  // 切换其他音乐
  async handleSwitch(event) {
    const data = event.currentTarget.dataset;
    let music = {};
    // 从播放列表取出当前要播放的音乐
    this.data.playerList.forEach(item => {
      if(item.id === data.id) {
        music = item;
      }
    })
     this.setData({isPlaying: false, isShowPlayList: false}); 
     // 关闭当前播放的音乐
     backgroundAudioManager.stop()

     app.setPlayMusicId(music.id);
     // 判断是否收藏
     await this.selectIsCollect(music.id);
     // 添加最近播放歌曲数据
     await this.addRecentListenMusic(music.id);
     // 获取歌词数据
     await this.getMusicLyricsList(music.id);
     // 歌词校准
     this.getCurrentLyricsIndex(0);
     // 开始播放
     this.setData({isPlaying: true, music: music});
     backgroundAudioManager.src = api.BASE_URL + "/music/view?filename=" + music.file;
     backgroundAudioManager.title = music.name;
     wx.showLoading({
      title: '歌曲加载中...',
      mask: true
    })
  },

  // 播放或暂停音乐
  playOrPauseMusic() {
    if(this.data.isPlaying) {
      // 播放中，则暂停
      backgroundAudioManager.pause();
    } else {
      // 暂停中，则播放
      backgroundAudioManager.play();
    }
    this.setData({isPlaying: !this.data.isPlaying});
  },

  // 获取个人歌单数据
  async getSelfMusicMenu() {
    const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
    const res = await myRequest({
      url: '/app/music/menu/getByUserId',
      method: 'POST',
      data: {token: loginUser}
    });
    if(res.data.code === 0) {
        let result = res.data.data;
        result.forEach((item, index) => {
          item.coverPhoto = api.BASE_URL + '/photo/view?filename=' + item.coverPhoto;
        })
        this.setData({musicMenuList: result});
    }
  },

  // 从播放列表移除某个歌曲
  async removeFromPlayList(event) {
    const data = event.currentTarget.dataset;
    const musicId = data.id;
    const { playerList, music } = this.data;
    // 如果当前播放列表只有一首歌，返回上级页面
    if(playerList.length === 1) {
      backgroundAudioManager.stop();
      app.setPlayMusicId('');
      this.setData({isPlaying: false});
      wx.navigateBack({
        delta: 1
      });
      return;
    }
    let musicIndex = 0;
    let newPlayerList = [];
    playerList.forEach((item, index) => {
      if(item.id === musicId) {
        musicIndex = index;
      } else {
        newPlayerList.push(item);
      }
    });
    this.setData({playerList: newPlayerList});
     // 判断是否移除当前正在播放的歌曲  自动切换下一首
     if(music.id === musicId) {
        backgroundAudioManager.stop();
        this.setData({isPlaying: false});
        let newMusic = {};
        if(playerList[musicIndex + 1]) {
          newMusic = playerList[musicIndex + 1];
        } else {
          // 播放第一首
          newMusic = playerList[0];
        }
        app.setPlayMusicId(newMusic.id);
        // 判断是否收藏
        await this.selectIsCollect(newMusic.id);
        // 添加最近播放歌曲数据
        await this.addRecentListenMusic(newMusic.id);
        // 获取歌词数据
        await this.getMusicLyricsList(newMusic.id);
        // 歌词校准
        this.getCurrentLyricsIndex(0);
        // 开始播放
        this.setData({isPlaying: true, music: newMusic});
        backgroundAudioManager.src = api.BASE_URL + "/music/view?filename=" + newMusic.file;
        backgroundAudioManager.title = newMusic.name;
        wx.showLoading({
         title: '歌曲加载中...',
         mask: true
       })
     }
  },

   // 进入评论页面
   goToComment() {
    wx.navigateTo({
      url: '/pages/comment/comment?musicId=' + this.data.music.id
    })
  },

  hideMusicList() {
    this.setData({
      isShowPlayList: false
    })
  },

  showMusicList() {
    this.setData({
      isShowPlayList: true
    })
  },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})